import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { env } from 'process'
import path from 'node:path'
import autoprefixer from 'autoprefixer'
import purgeCss from '@fullhuman/postcss-purgecss' // 移除未使用的css
import { compression } from 'vite-plugin-compression2'
import { ViteImageOptimizer } from 'vite-plugin-image-optimizer'
import inspect from 'vite-plugin-inspect'
import vueJsx from '@vitejs/plugin-vue-jsx'
import vueSetupExtend from 'vite-plugin-vue-setup-extend'
import packageJson from './package.json' assert { type: 'json' }

const { runEnv, NODE_ENV } = env
export default defineConfig({
  plugins: [
    vue(),
    vueJsx(),
    inspect(),
    vueSetupExtend(),
    ViteImageOptimizer(),
    compression({
      threshold: 1024 * 10,
      deleteOriginalAssets: true,
    }),
  ],
  optimizeDeps: {
    // Vite 会自动预构建项目中所有从 node_modules 引入的 ESM（ECMAScript 模块）依赖
    exclude: ['vue'],
  },
  resolve: {
    alias: [{ find: '@', replacement: '/src' }],
  },
  css: {
    preprocessorOptions: {
      scss: {
        additionalData:
          "$mainColor: #0f5dfc; @import '/src/assets/styles/common.scss';",
      },
    },
    postcss: {
      plugins: [
        autoprefixer,
        ...(NODE_ENV === 'production'
          ? [
              purgeCss({
                content: ['src/**/*.vue'],
                defaultExtractor(content) {
                  const contentWithoutStyleBlocks = content.replace(
                    /<style[^]+?<\/style>/gi,
                    '',
                  )
                  return (
                    contentWithoutStyleBlocks.match(
                      /[A-Za-z0-9-_/:]*[A-Za-z0-9-_/]+/g,
                    ) || []
                  )
                },
                safelist: ['test', /^jz-/],
              }),
            ]
          : []),
      ],
    },
  },
  esbuild: {
    drop: NODE_ENV === 'production' ? ['console', 'debugger'] : [],
  },
  build: {
    assetsInlineLimit: 1024 * 8,
    rollupOptions: {
      external: ['dayjs'], // dayjs 不需要打包
      input: {
        main: path.resolve(__dirname, 'index.html'),
        nested: path.resolve(__dirname, 'nested.html'),
      },
      output: {
        globals: {
          dayjs: 'dayjs',
        },
        entryFileNames: 'js/entry/[name]-[hash:10].js',
        chunkFileNames: 'js/chunk/[name]-[hash:10].js',
        assetFileNames: (assetInfo) => {
          const { name = '' } = assetInfo
          if (/\.(png|jpe?g|gif|svg|webp|bmp|tiff?)$/.test(name)) {
            return 'assets/images/[name]-[hash:10][extname]'
          } else if (/\.(ttf|otf|woff2?|eot|gif)$/.test(name)) {
            return 'assets/fonts/[name]-[hash:10][extname]'
          } else if (/\.css$/.test(name)) {
            return 'assets/styles/[name]-[hash:10][extname]'
          } else {
            return 'assets/[ext]/[name]-[hash:10][extname]'
          }
        },
        manualChunks: function (id) {
          if (id.includes('node_modules')) {
            if (id.includes('/node_modules/lodash-es/')) {
              return 'lodash-es'
            } else if (
              id.includes('/node_modules/vue/') ||
              id.includes('/node_modules/@vue/')
            ) {
              return 'vue-js'
            } else if (id.includes('/node_modules/vue-router/')) {
              return 'vue-router'
            } else if (id.includes('/node_modules/element-plus/')) {
              return 'element-plus'
            } else {
              return 'vendor'
            }
          } else if (id.includes('src/router/')) {
            return 'router-list'
          }
        },
      },
    },
  },
  define: {
    'import.meta.env.runEnv': JSON.stringify(`${runEnv}`),
    'APP_VERSION': JSON.stringify(`v${packageJson.version}`),
  },
  envDir: 'env-config',
  cacheDir: 'node_modules/.cache-vite',
})

// 图片转base64插件只用于本地、线上的环境 可替换 assetsInlineLimit
// const imageToBase64Plugin = (limit = 1024 * 4) => {
//     return {
//         name: "base64-set-plugin",
//         async transform(src: string, id: string) {
//             if (!/\.(png|jpe?g)$/.test(id)) return;
//             const statData = await stat(id);
//             if (statData.size > limit) return;
//             const buffer = await readFile(id);
//             const base64 = buffer.toString("base64");
//             const dataUrl = `data:image/${path.extname(id).split(".").pop()};base64,${base64}`;
//             return {
//                 code: `export default ${JSON.stringify(dataUrl)}`,
//                 initCode: src
//             };
//         },
//     };
// };
